package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 *
 * @author kangdi
 * @date 2025-05-25
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备信息列表
     *
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     *
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备信息
     *
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备信息
     *
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息信息
     *
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    /**
     * 删除设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(DeviceDto dto) {

        //删除云端
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(dto.getIotId());
        client.deleteDevice(request);
        //删除本地
        Device device = this.lambdaQuery().eq(Device::getIotId, dto.getIotId()).one();
        if(device==null){
            throw new BaseException("要删除的这个设备不存在");
        }
        int i = this.deleteDeviceById(device.getId());
        if (!(i > 0)){
            throw new BaseException("本地设备没删除掉");
        }

    }

    /**
     * 修改设备备注名称
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyDecive(DeviceDto dto) {
        //1.根据dto查出本地设备
        String nickname = dto.getRegisterDeviceRequest().getNickname();
        if (StringUtils.isBlank(nickname)){
            throw new BaseException("该设备没有备注名称");
        }
        Device device = this.getById(dto.getId());
        if(device==null){
            throw new BaseException("设备为空");
        }
        //2.修改云端
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        UpdateDevice body = new UpdateDevice();
        body.setDescription(nickname);
        request.withDeviceId(device.getIotId());
        request.withBody(body);
        try {
            client.updateDevice(request);//修改云端
            device.setNickname(nickname);//修改本地
            boolean result = this.updateById(device);
            if (!result){
                throw new BaseException("更新设备信息失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName) {
        //1. 判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).select(Device::getIotId).one();
        if(device==null) {
            throw new BaseException("设备不存在");
        }
        String deviceId = device.getIotId();//获取设备id

        //2. 调用华为云IOT接口查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if(response==null || response.getHttpStatusCode()!=200) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据失败");
        }

        //3. 解析响应结果数据，封装map的数据
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if(CollUtil.isEmpty(shadowDataList)) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据为空");
        }
        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();
        //事件操作时间，格式：yyyyMMdd'T'HHmmss'Z'，如20151212T121212Z。该值是国际标准时间，比东八区早八小时
        String eventTimeStr = reported.getEventTime();//数据上报时间
        //转为东八区时间
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        List<Map<String,Object>> propertyStatusInfo = new ArrayList<>();
        properties.forEach((k,v)->{
            //封装属性对象
            Map<String,Object> propertyMap = new HashMap<>();
            propertyMap.put("identifier",k);
            propertyMap.put("name",k);
            propertyMap.put("value",v);
            propertyMap.put("time",eventTime);
            propertyStatusInfo.add(propertyMap);
        });

        //4. 返回Map数据
        Map<String,Object> resultMap = new HashMap<>();

        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo", propertyStatusInfo);

        resultMap.put("list",propertyStatusInfoMap);

        return resultMap;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param productKey
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //1.调用华为云IOT接口查询产品详情
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("调用华为云IOT接口查询产品详情失败");
        }
        //2.解析响应结果
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)) {
            throw new BaseException("没有查到物模型数据");
        }
        ServiceCapability serviceCapability = serviceCapabilities.get(0);
        //3.数据类型转换,把一个对转成JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(serviceCapability);
        return jsonObject;
    }

    /**
     * 获取设备详细信息
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //根据设备ID从表中查询设备，不存在抛异常
        Device device = this.lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();
        if (device == null) {
            throw new BaseException("没有查询到设备");
        }
        //拷贝表中设备数据给VO
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, vo);

        vo.setDeviceSecret(device.getSecret());
        vo.setGmtCreate(device.getCreateTime());
        SysUser sysUser = userService.selectUserById(Long.valueOf(device.getCreateBy()));
        vo.setCreator(sysUser.getUserName());
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());
        //调用华为IOT平台接口查询设备
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("调用华为云IOT接口获取设备详情失败");
        }
        //把华为中部分的设备数据给VO（deviceStatus）
        vo.setDeviceStatus(response.getStatus());
        vo.setStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotBlank(activeTimeStr)) {
            LocalDateTime gmtActive = OffsetDateTime.parse(activeTimeStr).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setGmtActive(gmtActive);
        }
        vo.setFirmwareVersion(response.getFwVersion());
        //返回vo
        return vo;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(DeviceDto dto) {
        //1.设备名称是否重复 select count(*) from device where device_name = ?
        Long countDeviceName = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (countDeviceName > 0) {
            throw new BaseException("设备重名");
        }
        //2.设备标识是否重复 select count(*) from device where node_id = ?
        String nodeId = IdUtil.getSnowflakeNextIdStr();//生成19位长度的唯一值当做设备的唯一标识
        Long countNodeId = this.lambdaQuery().eq(Device::getNodeId, nodeId).count();
        if (countNodeId > 0) {
            throw new BaseException("设备标识码重复");
        }
        //3.同一位置是否绑定了相同的产品 select count(*) from device where product_key =? and location_type=? and binding_location=?
        Long countLocation = this.lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .count();
        if (countLocation > 0) {
            throw new BaseException("该位置已经绑定过同类型的产品");
        }
        //4.调用华为IOT注册设备

        String description = dto.getRegisterDeviceRequest().getNickname();

        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(nodeId);//必填参数
        body.setProductId(dto.getProductKey());//设备管理的产品id(产品唯一标识）
        body.setDeviceName(dto.getDeviceName());
        body.setDescription(description);

        String secret = IdUtil.fastSimpleUUID();//设备密钥UUID唯一值
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);//设备密钥
        body.setAuthInfo(authInfo);

        request.withBody(body);
        AddDeviceResponse response = client.addDevice(request);
        if (response == null || response.getHttpStatusCode() != 201) {
            throw new BaseException("调用IOT接口注册设备失败");
        }
        //5.解析响应结果
        String iotId = response.getDeviceId();

        //6.更新设备到表中
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setIotId(iotId);
        device.setSecret(secret);
        device.setNodeId(nodeId);
        device.setDeviceDescription(description);
        device.setNickname(description);

        device.setProductName(getProductNameFromCache(dto.getProductKey()));

        boolean result = this.save(device);
        if (!result) {
            throw new BaseException("新增设备失败");
        }

    }

    private String getProductNameFromCache(String productKey) {
        //1.查询Redis产品列表的JSON字符串
        String productJSON = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        //2.解析字符串为产品列表
        List<ProductSummary> productSummaryList = JSONUtil.toList(productJSON, ProductSummary.class);
        //3.获取列表中对应产品id的产品对象
        ProductSummary productSummary = productSummaryList.stream().filter(x -> x.getProductId().equals(productKey)).findFirst().get();
        //4.获取该对象的产品名
        if (productSummary != null) {
            return productSummary.getName();
        }
        return null;
    }

    /**
     * 查询所有产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        //1.从Redis查询产品列表JSON字符串
        String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        //2.把JSON字符串解析为产品列表
        if (StringUtils.isBlank(productListJson)) {
            throw new BaseException("产品列表不存在");
        }
        //3.将每个产品类型转化为ProductVo
        List<ProductSummary> productSummaryList = JSONUtil.toList(productListJson, ProductSummary.class);
        List<ProductVo> productVoList = productSummaryList.stream().map(productSummary -> {
            return ProductVo.builder().productName(productSummary.getName()).productKey(productSummary.getProductId()).build();

        }).collect(Collectors.toList());
        //4.组装返回数据
        return productVoList;

    }

    /**
     * 同步接口，同步IOT平台产品
     */
    @Override
    public void syncProductList() {
        //1.调用IOT平台接口，查询产品列表
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        if (response == null || response.getHttpStatusCode() != 200) {
            throw new BaseException("获取产品列表失败");
        }
        List<ProductSummary> productsList = response.getProducts();
        //2.讲产品列表保存到Redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(productsList));


    }
}
